use std::fs::{self, metadata, read_dir};
use std::io::Read;
use std::path::PathBuf;
use std::result::Result;

#[tauri::command]
pub fn read_files_contents(file_paths: Vec<PathBuf>) -> Result<Vec<String>, String> {
    let mut results = Vec::new();
    for path in file_paths {
        let mut file = match fs::File::open(&path) {
            Ok(file) => file,
            Err(e) => return Err(format!("无法打开文件 {}: {}", path.display(), e)),
        };
        let mut contents = String::new();
        if let Err(e) = file.read_to_string(&mut contents) {
            return Err(format!("无法读取文件 {}: {}", path.display(), e));
        };
        results.push(contents);
    }
    Ok(results)
}

#[tauri::command]
pub fn get_files_path(root_path: &str) -> Result<Vec<String>, String> {
    let mut path_list = vec![String::from(root_path)];
    let mut start_index = 0;
    loop {
        let list_len = path_list.len();
        for index in start_index..path_list.len() {
            let path = &path_list[index];
            match metadata(path) {
                Ok(metadata) => {
                    if metadata.is_dir() {
                        for child_dir in read_dir(&path).expect("") {
                            path_list.push(String::from(
                                child_dir.expect("").path().as_os_str().to_str().expect(""),
                            ));
                        }
                    }
                }
                Err(_) => {}
            }
        }
        if list_len == start_index {
            break;
        }
        start_index = list_len;
    }
    return Ok(path_list);
}
